package com.raquel.onceuponatime;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Class for delete a existing tale from database
 * Servlet implementation class Delete
 * @author raquel_valenzuela
 */
@WebServlet("/Delete")
public class Delete extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Delete() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		deleteTale(request.getParameter("id"));
		this.getServletContext().getRequestDispatcher("/Home").forward(request, response);
	}
	
	/**
	 * deletes a tale from database
	 * @param id
	 */
	private void deleteTale(String id) {
		// TODO Auto-generated method stub
		String urlcon="jdbc:mysql://localhost:3306/onceupon";
		
		try{
		Class.forName("com.mysql.jdbc.Driver");
		Connection conn = (Connection)DriverManager.getConnection(urlcon,"root","");
		
		String insertSQL="delete from tale where id=?";
		PreparedStatement prep= conn.prepareStatement(insertSQL);
		
		prep.setString(1,id);
		prep.executeUpdate();
		
		prep.close();
		conn.close();
		
		}catch (SQLException e){
			e.printStackTrace();
			
		}catch(ClassNotFoundException e){
			e.printStackTrace();
			
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.getServletContext().getRequestDispatcher("/Home").forward(request, response);
	}

}
